package tcplib

import (
	"cow_golang/shared_mod/tcplib/iface"
	"errors"
	"fmt"
	"sync"
)

type SessionManager struct {
	sessions map[uint32]iface.ISession
	rwMu     sync.RWMutex
}

func NewSessionManager() *SessionManager {
	return &SessionManager{
		sessions: make(map[uint32]iface.ISession),
	}
}

// Add 加入新session
func (s *SessionManager) Add(session iface.ISession) {
	// 加锁
	s.rwMu.Lock()
	defer s.rwMu.Unlock()
	//	加入管理
	s.sessions[session.GetID()] = session
	fmt.Println("add session to manager id:", session.GetID(),
		" total:", s.Len())
}

// Remove 删除session
func (s *SessionManager) Remove(session iface.ISession) {
	// 加锁
	s.rwMu.Lock()
	defer s.rwMu.Unlock()
	delete(s.sessions, session.GetID())
	fmt.Println("remove session from manager id:", session.GetID(),
		" total:", s.Len())
}

// GetSession 通过id获取session
func (s *SessionManager) GetSession(id uint32) (iface.ISession, error) {
	// 加锁
	s.rwMu.Lock()
	defer s.rwMu.Unlock()
	if session, ok := s.sessions[id]; ok {
		return session, nil
	} else {
		return nil, errors.New("session not found")
	}
}

// Len 获取当前连接总数
func (s *SessionManager) Len() int {
	return len(s.sessions)
}

// Clear 停止并删除所有连接
func (s *SessionManager) Clear() {
	// 加锁
	s.rwMu.Lock()
	defer s.rwMu.Unlock()
	// 停止并删除全部连接
	for id, session := range s.sessions {
		// 停止
		session.Stop()
		delete(s.sessions, id)
	}
	fmt.Println("clear all sessions success total:", s.Len())
}
